/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.amitycs.collabdrawing.server;

import java.awt.Shape;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.amitycs.collabdrawing.Constants;
import org.amitycs.collabdrawing.Whiteboard;

/**
 *
 * @author joe
 */
public class Server {

    private Listener listener;
    private MulticastSocket multisock;
    private Whiteboard whiteboard;

    public static void main(String[] args) throws Exception
    {
        new Server();
        /*
        MulticastSocket multisock = new MulticastSocket(null);
        byte[] buf = new byte[65536];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        multisock.receive(packet);
        System.out.println("Received packet");
        multisock.send(packet); */
    }

    public Server() {
        initServer();
        whiteboard = new Whiteboard();
    }

    private void initServer() {
        try {
            multisock = new MulticastSocket(Constants.GROUP_PORT);
            multisock.setReuseAddress(true);
            multisock.joinGroup(InetAddress.getByName(Constants.GROUP_IP));
            //multisock.bind(new InetSocketAddress(Constants.GROUP_IP,Constants.GROUP_PORT));
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }

        listener = new Listener();
        new Thread(listener).start();

    }

    private void kill() {
        listener.kill();
        multisock.close();
    }

    private class Listener implements Runnable {

        private boolean running = true;

        private void kill() {
            running = false;
        }

        public void run() {
            System.out.println("starting server listener");
            while (running) {
                try {
                    byte[] buf = new byte[65536];
                    DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    multisock.receive(packet);
                    System.out.println("Received packet");
                    multisock.send(packet);
                    ByteArrayInputStream bais = new ByteArrayInputStream(buf);
                    ObjectInputStream ois = new ObjectInputStream(bais);
                    Shape shape = (Shape) ois.readObject();
                    bais.close();
                    ois.close();

                    whiteboard.addShape(shape);
                } catch (Exception e) {
                    //ignore
                }
            }
        }
    }
}
